<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addrolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <!-- row-key="id" 是2019年3月提供的新特性，
if there's nested data, rowKey is required.
如果这是一个嵌套的数据，rowkey 是必须添加的属性 -->
      <el-table :data="roleList" border stripe>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
           <template slot-scope="scope">
        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                    {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二，三级权限 -->
            <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                    <el-col :span="6">
                        <el-tag type="success" closable  @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                        <el-tag type="warning" closable v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)" > 
                            {{item3.authName}}
                        </el-tag>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editrole(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delrole(scope.row.id)"
              >删除</el-button
            >
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="添加角色"
      :visible.sync="addrolesDialogVisible"
      width="50%"
      @close="addrolesDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addroleslist"
        ref="addrolesFormref"
        label-width="100px"
        :rules="addrolesFormrules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addroleslist.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addroleslist.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addrolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addroles">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="添加角色"
      :visible.sync="editrolesDialogVisible"
      width="50%"
      @close="editrolesDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="editroleslist"
        ref="editrolesFormref"
        label-width="100px"
        :rules="editrolesFormrules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editroleslist.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editroleslist.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addrolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editroles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
<el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
    <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
    <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      addrolesDialogVisible: false,
      addroleslist: {
        roleName: "",
        roleDesc: "",
      },
      addrolesFormrules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
      editrolesDialogVisible: false,
      editrolesFormrules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
    editroleslist: {},
    setRightDialogVisible:false,
    rightsList:[],
    //树形控件的属性绑定对象
    treeProps: {
        //通过label设置树形节点文本展示authName
        label: 'authName',
        //设置通过children属性展示子节点信息
        children: 'children'
      },
      //设置树形控件中默认选中的内容
      defKeys:[],
      roleId:''
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      //如果返回状态为异常状态则报错并返回
      // if (res.meta.status !== 200)
      //     return this.$message.error('获取角色列表失败')
      // //如果返回状态正常，将请求的数据保存在data中
      // this.roleList = res.data
      console.log(res.data);
      this.roleList = res.data;
    },
    addrolesDialogClosed() {
      this.$refs.addrolesFormref.resetFields();
    },
    addroles() {
      this.$refs.addrolesFormref.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写完整角色信息");
        //发送请求完成修改用户的操作
        const { data: res } = await this.$http.post(
          "roles/",
          this.addroleslist
        );
        //判断如果修改失败，就做提示
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        //修改成功的提示
        this.$message.success("添加角色成功");
        //关闭对话框
        this.addrolesDialogVisible = false;
        //重新请求最新的数据
        this.getRoleList();
      });
    },
    async delrole(id) {
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.err("角色删除失败");
      }
      this.$message.success("角色删除成功");
      this.getRoleList();
    },
    editrolesDialogClosed() {
      this.$refs.editrolesFormref.resetFields();
    },
    editrole(role){
        
        const {roleName,roleDesc,id}=role
        this.editroleslist={roleName,roleDesc,id}
        this.editrolesDialogVisible=true
    },
    async editroles(){
         const {roleName,roleDesc,id}=this.editroleslist
        const { data: res } = await this.$http.put('roles/'+id, {roleName,roleDesc})
        if(res.meta.status !== 200) {
            return this.$message.err('角色编辑失败')
        }
        this.$message.success('角色修改成功') 
       
              this.getRoleList();
               this.editrolesDialogVisible=false
        
  },
  async removeRightById(role,rightId){
    //弹窗提示用户是否要删除
    const confirmResult = await this.$confirm('请问是否要删除该权限','删除提示',{
        confirmButtonText:'确认删除',
        cancelButtonText:'取消',
        type:'warning'
    }).catch(err=>err)
    //如果用户点击确认，则confirmResult 为'confirm'
    //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
    if(confirmResult != "confirm"){
        return this.$message.info("已经取消删除")
    }

    //用户点击了确定表示真的要删除
    //当发送delete请求之后，返回的数据就是最新的角色权限信息
    const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
    if (res.meta.status !== 200)
        return this.$message.error('删除角色权限失败')

    //无需再重新加载所有权限
    //只需要对现有的角色权限进行更新即可
    role.children = res.data
    // this.getRoleList();
 
},
//展示分配权限的对话框
  async showSetRightDialog(role){
    this.roleId=role.id
       const { data: res } = await this.$http.get('rights/tree')
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      //如果返回状态正常，将请求的数据保存在data中
      this.rightsList = res.data

      //调用getLeafKeys进行递归，将三级权限添加到数组中
      this.getLeafKeys(role, this.defKeys)
      //当点击分配权限按钮时，展示对应的对话框
      this.setRightDialogVisible = true
      console.log(this.defKeys)
    
  },
   getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      //递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose(){
      this.defKeys=[]
    },
      async allotRights() {
      //当用户在树形权限对话框中点击确定，将用户选择的
      //权限发送请求进行更新

      //获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')

      //发送请求完成更新
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids:idStr }
      )
      if (res.meta.status !== 200)
        return this.$message.error('分配权限失败')

      this.$message.success("分配权限成功")
      this.getRoleList();
      //关闭对话框
      this.setRightDialogVisible = false;
    }
}
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-tag{
  margin: 15px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
border-bottom: 1px solid #eee;
}
.el-table{
  margin-top: 10px;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>